<div id="formDiv"></div>
<script type="text/html" id="warehouseProductionOrderformContent">
  <form lay-filter="warehouseProductionOrderForm" id="warehouseProductionOrderForm" class="layui-form open-form">
    <div class="open-model">
      <div class="open-auto">
        <div>
          <div class="layui-form-item layui-row">
            <input name="id" type="hidden" />
            <input name="productId" id="productId" type="hidden" />

             <div class="layui-inline layui-col-md3">
              <label class="layui-form-label" style="width: 100px">出库类型</label>
              <input type="text" name="inventoryTypeName" id="inventoryTypeName" id="inventoryTypeName" hidden  />
              <div class="layui-input-block" style="margin-left: 130px">
                <select id="inventoryTypeId" name="inventoryTypeId" lay-filter="inventoryTypeId" lay-search lay-verify="required"></select>
              </div>
            </div>

            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label"> 制造令</label>
              <input class="layui-input adv-disable" id="productionSchedulingPlanDetailId"  lay-filter="productionSchedulingPlanDetailId"  name="productionSchedulingPlanDetailId" type="hidden"/>
<!--              <input name="productionSchedulingPlanDetailCode" id="productionSchedulingPlanDetailCode" type="hidden" />-->
              <div class="layui-input-block">
                <input class="layui-input adv-disable" id="productionSchedulingPlanDetailCode"  lay-filter="productionSchedulingPlanDetailCode" placeholder="请选择制令单" readonly name="productionSchedulingPlanDetailCode" lay-search required />

<!--                <select id="productionSchedulingPlanDetailId" name="productionSchedulingPlanDetailId" lay-filter="productionSchedulingPlanDetailId"  lay-search required></select>-->
              </div>
            </div>

            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">所属客户</label>
              <div class="layui-input-block">
                <input class="layui-input adv-disable" id="customerName"  lay-filter="customerName" disabled name="customerName" />
              </div>
            </div>
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">客户ID</label>
              <div class="layui-input-block">
                <input class="layui-input adv-disable" id="customerId"  lay-filter="customerId" disabled name="customerId" />
              </div>
            </div>
          
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">所属生产订单</label>
              <div class="layui-input-block">
                <input type="hidden" id="productionOrderId" disabled  lay-filter="productionOrderId" name="productionOrderId" />
                <input class="layui-input adv-disable" id="productionOrderNumber" lay-filter="productionOrderNumber" disabled name="productionOrderNumber" />
              </div>
            </div>
            <!-- <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">加工方式</label>
              <div class="layui-input-block">
                <select id="processingType" name="processingType" lay-filter="processingType"  lay-search required></select>
              </div>
            </div> -->
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">厚度/壁厚/直径</label>
              <div class="layui-input-block">
                <input class="layui-input adv-disable" id="diameter"  lay-filter="diameter" disabled name="diameter" />
              </div>
            </div>

            <!-- <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">产成品料号</label>
              <div class="layui-input-block">
                <input type="text" class="layui-input" disabled id="customerProductCode" name="customerProductCode" />
              </div>
            </div> -->
            <!-- <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">产成品规格码</label>
              <div class="layui-input-block">
                <input type="text" class="layui-input" disabled id="productSpecCode" name="productSpecCode" />
              </div>
            </div> -->


          </div>
          <div class="layui-form-item layui-row">

            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">计划产量</label>
              <div class="layui-input-block">
                <input class="layui-input adv-disable" id="plannedQuantity" disabled name="plannedQuantity" />
              </div>
            </div>
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">材料料号</label>
              <!-- <input type="hidden" name="materialNumber" id="materialNumber" /> -->
              <div class="layui-input-block">
                <input class="layui-input adv-disable" id="materialNumber" disabled name="materialNumber" />
              </div>
            </div>

            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">计划交货时间</label>
              <div class="layui-input-block">
                <input type="text" class="layui-input " id="deliveryTime" disabled name="deliveryTime" />
              </div>
            </div>
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">宽度/外径</label>
              <div class="layui-input-block">
                <input type="text" class="layui-input " id="warehouseWidth" disabled name="warehouseWidth" />
              </div>
            </div>
          </div>

          <div class="layui-form-item layui-row">

            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">品种</label>
              <div class="layui-input-block">
                <input class="layui-input adv-disable" id="productVarietyName" disabled name="productVarietyName" />
              </div>
            </div>
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">牌号</label>
            
              <div class="layui-input-block">
                <input class="layui-input adv-disable" id="productMarkName" disabled name="productMarkName" />
              </div>
            </div>

            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">生产商</label>
              <div class="layui-input-block">
                <input type="text" class="layui-input " id="productProducerName" disabled name="productProducerName" />
              </div>
            </div>
            
          </div>
          <div class="layui-form-item layui-row">
            
            <!-- <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">选择车间</label>
              <input type="hidden" name="workshopId" id="workshopId" />
              <div class="layui-input-block">
                <input type="text" class="layui-input"  disabled name="workshopName" />
              </div>
            </div> -->
             <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">选择产线</label>
              <input type="hidden" name="productionLineId" lay-filter="productionLineId"  id="productionLineId" />
              <div class="layui-input-block">
                <input type="text" class="layui-input" disabled name="productionLineName" lay-filter="productionLineName"  />
              </div>
            </div>
          </div>
          <div class="layui-form-item layui-row">
            <div class="layui-inline layui-col-md3">
              <label class="layui-form-label">生产计划备注</label>
              <div class="layui-input-block">
                <input type="text" class="layui-input" disabled lay-filter="productionPlanRemark" name="productionPlanRemark"  id="productionPlanRemark"  />
              </div>
            </div>


           </div>

        <div class="layui-form-item tableContent">
          <!-- {{# if(d.eventName !== 'detail'){ }} -->
          <!-- {{# } }} -->
          <table class="layui-table" id="warehouseMaterialRequisitionRecordFormTable" lay-filter="warehouseMaterialRequisitionRecordFormTable"></table>
        </div>

        <div class="layui-form-item text-right">
          <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">关闭</button>

         {{# if(d.eventName !== 'detail'){ }}
          <button class="layui-btn" lay-filter="formSubmit" type="button" lay-submit>提交</button>
        {{# } }}
        </div>
      </div>
    </div>
  </form>
</script>

<script type="text/html" id="warehouseMaterialRequisitionRecordFormTableBar">
  <button class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del" type="button">删除</button>
</script>


<script>
  layui.use(["layer", "form", "table", "admin", "laydate", "upload", "laytpl"], async function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var config = layui.config;
    var admin = layui.admin;
    var upload = layui.upload;
    let laydate = layui.laydate;
    let laytpl = layui.laytpl;
    const nowData = { ...parentData };
    let data = nowData?.data;
    let skuList = [];

    laytpl(warehouseProductionOrderformContent.innerHTML).render({ ...nowData }, function (html) {
      $("#formDiv").after(html);
    });
    // 初始化日期选择
    // await admin.initDataSelectPro("warehouse/warehouse/productionSchedulingPlanDetail/list", { limit: 99999 }, "productionSchedulingPlanDetailId", "制造令", async (d, obj) => {
    //   console.log(d, obj);
    //   $("#productionSchedulingPlanDetailCode").val("");
    //   if (d.value) { 
    //     $("#productionSchedulingPlanDetailCode").val(obj.code);
    //   }   
    // },);
    await admin.initDataSelectPro(
      "warehouse/warehouse/admin/warehouseProductInventoryType/list?inventoryType=out",
      {
        limit: 999
      },
      "inventoryTypeId",
      "出库类型",
      async (d, obj) => {
        // $("#warehouseProductId").empty();
        form.val("warehouseProductionOrderForm", {
          inventoryTypeName: ""
        });
        if (obj.name) {
          form.val("warehouseProductionOrderForm", {
            inventoryTypeName: obj.name
          });
          form.render()

        }
      },
      "name"
    );

    await admin.initDataSelectPro(
      "enterprise/dict/admin/dictLabel/list",
      {
        limit: 99999,
        dictType: "warehouse_processingType"

      },
      "processingType",
      "加工方式",
      (d) => {
        if (d.value) {
          // processingType = d.value;
        }
      },
      "labelName"
    );
    await admin.initDataSelectPro(
      "warehouse/warehouse/productionSchedulingPlanDetail/list?status=3",
      {
        limit: 99999
      },
      "productionSchedulingPlanDetailId",
      "制造令",
      async (d, obj) => {
        console.log(obj,"obj");
        form.val("warehouseProductionOrderForm", obj);
        if (d.value) {
          $("#productionSchedulingPlanDetailCode").val(obj.code);
          if (obj.materialNumber) {

            const materialList = (obj.materialNumber || '').split(',').filter(item => item.trim() !== '');
            // 将数组包装成对象，并用 JSON.stringify 序列化
            let res = admin.req(
              "warehouse/warehouse/productInventory/selectMaterialDetail",
              JSON.stringify(materialList),
              function (nowRes) {
                table.reload("warehouseMaterialRequisitionRecordFormTable", {
                  data: nowRes.data,
                });
                console.log(nowRes);
              },
              "POST",
              false,
              "application/json"
            );


          }

        } else {
          if (nowData.eventName === "detail") {

            return;
          }
          table.reload("warehouseMaterialRequisitionRecordFormTable", {
            data: [],
          });
          form.val("warehouseProductionOrderForm", {
            id: "",                         // 隐藏字段
            productId: "",                  // 隐藏字段
            productionOrderNumber: "",      // 禁用字段
            customerProductCode: "",        // 禁用字段
            productSpecCode: "",            // 禁用字段
            plannedQuantity: "",             // 禁用字段
            materialNumber: "",              // 隐藏字段
            productionSchedulingPlanDetailCode: "", // 隐藏字段
            productionSchedulingPlanDetailId: "",    // 下拉框
            workshopId: "",                  // 隐藏字段
            workshopName: "",                // 禁用字段
            productionLineId: "",            // 隐藏字段
            productionLineName: "",          // 禁用字段
            plannedProductionTime: "",
            productionOrderId: "",           // 隐藏字段
            deliveryTime: "",
            diameter: "",
            productProducerName: "",
            productVarietyName: "",
            productMarkName: "",
            warehouseWidth: "",              // 禁用字段
            productionPlanRemark: "",        // 禁用字段
            // warehouseName: "",               // 隐藏字段
            // warehouseId: ""                  // 下拉框
          });
        }
        form.render();
      },
      "code"
    );

    $("#productionSchedulingPlanDetailCode").click(function () {
      if (nowData.eventName === "detail") {
        return;
      }
      admin.formOpen({
        area: "90%",
        offset: ['6%', '6%'],
        title: "选择制造令",
        path: "components/warehouse/product/warehouseMaterialRequisitionRecordSelect.html",
        success: function () {
          // parentData.notIds = table.cache["purchasePlanFormTable"].map((v) => v.id);
          // parentData.customerId = $("#customerId").val();
          // parentData.productStatus  = 3
        },
        end: function () {
          if(childData.SelectList && childData.SelectList.length){
          let data=childData.SelectList[0]
          form.val("warehouseProductionOrderForm", data);
          $("#productionSchedulingPlanDetailCode").val(data.code);
          $("#productionSchedulingPlanDetailId").val(data.id);
          if (data.materialNumber) {
            const materialList = (data.materialNumber || '').split(',').filter(item => item.trim() !== '');
            // 将数组包装成对象，并用 JSON.stringify 序列化
            let res = admin.req(
                    "warehouse/warehouse/productInventory/selectMaterialDetail",
                    JSON.stringify(materialList),
                    function (nowRes) {
                      table.reload("warehouseMaterialRequisitionRecordFormTable", {
                        data: nowRes.data,
                      });
                      console.log(nowRes);
                    },
                    "POST",
                    false,
                    "application/json"
            );


          }
          }
        }
      });
    })



    const tableVal = table.render({
      elem: "#warehouseMaterialRequisitionRecordFormTable",
      page: false,
      limit: 999999,
      height: 400,
      data: [],
      cols: [
        [
          { type: "numbers", title: "序号" },
          { field: "userBundleCode", align: "center", title: "客户捆包号" },
          // { field: "sysBundleCode", align: "center", title: "内部捆包号" },
          { field: "warehouseName", title: "仓库" },
          { field: "warehouseAreaName", title: "库区" },
          { field: "warehouseShelfSpaceCode", title: "库位" },
             { field: "productProducer", title: "厂家" },
          { field: "productVariety", title: "品种" },
          { field: "productMark", title: "牌号" },
          // { field: "productBrand", title: "品牌" },
          { field: "productMainUnit", title: "单位" },
          { field: "grossWeight", title: "单位毛重" },
          { field: "netWeight", title: "单位净重" },
          // { field: "warehouseMaterialRequisitionRecordPerson", title: "入库作业人" },
          // { field: "warehouseMaterialRequisitionRecordTime", title: "入库作业时间" },
          {
            title: "操作", toolbar: "#warehouseMaterialRequisitionRecordFormTableBar",
            hide: nowData.eventName === "detail"
          }
        ]
      ]
    });
    if (nowData.eventName === "detail") {
      // admin.setFormDisable("#warehouseProductionOrderForm", true);
      console.log(nowData);
      $("#processingType").attr("disabled", "disabled");

      $("#inventoryTypeId").attr("disabled", "disabled");
      $("#productionSchedulingPlanDetailId").attr("disabled", "disabled");
      // 重新渲染表单
      form.render('select');
      form.val("warehouseProductionOrderForm", nowData.data)
      form.render();
      table.reload("warehouseMaterialRequisitionRecordFormTable", {
        data: nowData.data.warehouseMaterialRequisitionRecordDetailList,
      })
    }
    if (data && data.id) {
      if (nowData.eventName === "detail") {
        return
      }
      const res = await admin.reqPro("warehouse/warehouse/productionSchedulingPlan/selectProductionSchedulingPlanDetail", { id: data.productionPlanId });
      admin.initDataSelect(res.data.warehouseProductionSchedulingPlanDetailList, {}, "productionSchedulingPlanDetailId", data.productionSchedulingPlanDetailId, "制造令", "code", "id");
      table.reload("warehouseMaterialRequisitionRecordFormTable", {
        data: data.warehouseMaterialRequisitionRecordDetailList
      });
      form.on("select(productionSchedulingPlanDetailId)", function (d) {
        form.val("warehouseProductionOrderForm", { workshopName: "", productionLineName: "", plannedProductionTime: "", productionPlanRemark: "" });
        if (d.value) {
          const obj1 = data.warehouseProductionSchedulingPlanDetailList.find((v) => v.id == d.value);
          form.val("warehouseProductionOrderForm", { ...obj1, productionPlanRemark: obj1.remark, productionSchedulingPlanDetailCode: obj1.code });
        }
      });
      form.val("warehouseProductionOrderForm", { ...data, customerProductCode: data.productCode });
      $("#materialDetail").text(data.materialNumber ? data.materialNumber : "无物料");
      $("#materialDetail").attr("title", data.materialNumber ? data.materialNumber : "无物料");

    }

    form.on("submit(formSubmit)", function (d) {
      let formData = { ...d.field };
      formData.warehouseMaterialRequisitionRecordDetailList = table.cache["warehouseMaterialRequisitionRecordFormTable"];

      const requiredFields = [
        { field: 'productionSchedulingPlanDetailId', msg: '请选择制造令' },

      ];

      for (const { field, msg } of requiredFields) {
        if (!formData[field]) {
          layer.msg(msg);
          return;
        }
      }
      if (nowData.eventName == "add") {
        delete formData.id;
        console.log(formData);
        formData.requisitionQuantity = table.cache["warehouseMaterialRequisitionRecordFormTable"].length;
        admin.req(
          "warehouse/warehouse/materialRequisitionRecord/add",
          JSON.stringify(formData),
          function (res) {
            layer.closeAll("loading");
            if (res.code == 200) {
              layer.msg(res.msg, { icon: 1 });
              table.reload("ProductionOrderTable");
              layer.closeAll("page");
            } else {
              layer.msg(res.msg, { icon: 2, time: 1000 });
            }
          },
          "POST",
          false,
          "application/json"
        );
      } else if (nowData.eventName == "edit") {
        admin.req(
          "warehouse/warehouse/productionSchedulingPlan/update",
          JSON.stringify(formData),
          function (res) {
            layer.closeAll("loading");
            if (res.code == 200) {
              layer.msg(res.msg, { icon: 1 });
              table.reload("ProductionOrderTable");
              layer.closeAll("page");
            } else {
              layer.msg(res.msg, { icon: 2, time: 1000 });
            }
          },
          "POST",
          false,
          "application/json"
        );
      }
      return false;
    });
    table.on("tool(warehouseMaterialRequisitionRecordFormTable)", function (obj) {
      var d = obj.data; // 获取当前行的数据
      var layEvent = obj.event; // 获取事件名（edit 或 del）
      if (obj.tr) {
        obj.tr.on("click", function (e) {
          e.preventDefault(); // 防止默认行为
        });
      }
      if (layEvent == "del") {
        const index = $(obj.tr[0]).data("index");
        let list = table.cache["warehouseMaterialRequisitionRecordFormTable"].filter((v) => {
          return v["LAY_TABLE_INDEX"] != index;
        });
        table.reload("warehouseMaterialRequisitionRecordFormTable", {
          data: list
        });
      }
    });
    $("#Configure").click(function () {
      admin.formOpen({
        area: "90%",
        offset: "10%",
        title: "物料详情",
        path: "/admin/components/warehouse/product/productDetailTable.html",
        success: function () {
          if (!$("#productId").val()) {
            layer.msg("请先选择产品");
            return false;
          }
          parentData.warehouseProductId = $("#productId").val();

          parentData.bundleCodeList = table.cache["warehouseMaterialRequisitionRecordFormTable"].map((v) => v.productDetailId);
        },
        end: function () {
          if (childData.list) {
            let list = [...childData.list, ...table.cache["warehouseMaterialRequisitionRecordFormTable"]];
            table.reload("warehouseMaterialRequisitionRecordFormTable", {
              data: list
            });
          }
        }
      });
    });
    // $("#materialDetail").click(function () {
    //   if (!$("#productionPlanId").val()) {
    //     layer.msg("请先选择生产计划");
    //     return false;
    //   }
    //   if ($("#materialNumber").val()) {
    //     let zindex = admin.formOpen({
    //       area: "90%",
    //       offset: "10%",
    //       title: "物料详情",
    //       content: $("#warehouseMaterialRequisitionRecordForm").html(),
    //       success: function () {
    //         // if (nowData.eventName === "detail") {
    //         //   admin.setFormDisable("#warehouseMaterialRequisitionRecordForm", true);
    //         // }
    //         // parentData.list = d.materialNumber;
    //         admin.req(
    //           "warehouse/warehouse/product/list",
    //           {
    //             limit: 999999,
    //             productIds: $("#materialNumber").val().split(",")
    //           },
    //           (res) => {
    //             table.render({
    //               elem: "#warehouseMaterialRequisitionRecordTable",
    //               // url: config.base + "warehouse/warehouse/product/list",
    //               data: res.data,
    //               page: false,
    //               cols: [
    //                 [
    //                   { field: "productVariety", align: "center", title: "品种" },
    //                   { field: "productCode", align: "center", title: "客户成品料号" },
    //                   { field: "productSpecCode", align: "center", title: "规格" },
    //                   { field: "diameter", align: "center", title: "厚度/壁厚/直径" },
    //                   { field: "width", align: "center", title: "宽度/外径" },
    //                   { field: "length", align: "center", title: "长度" },
    //                   { field: "productMainUnit", align: "center", title: "成品单位" }
    //                 ]
    //               ]
    //             });
    //           }
    //         );
    //       }
    //     });
    //   } else {
    //     layer.msg("当前产品未配置材料");
    //   }
    // });

    $("#warehouseProductionOrderForm .layui-table-body").css("overflow", "visible");
    $("#warehouseProductionOrderForm .layui-table-box").css("overflow", "visible");
    $("#warehouseProductionOrderForm .layui-table-view").css("overflow", "visible");
  });
</script>

<style>
  #warehouseProductionOrderForm .layui-form-label {
    width: 125px;
  }

  #warehouseProductionOrderForm .layui-input-block {
    margin-left: 155px;
  }

  #warehouseProductionOrderForm .layui-form-item .layui-inline {
    /* margin-bottom: 5px; */
    margin-right: 0px;
  }

  #warehouseProductionOrderForm .layui-table-cell {
    overflow: visible !important;
  }
</style>